package com.pro01.backend.mapper;

import com.pro01.backend.dto.UserConnectionStatusDTO;
import org.apache.ibatis.annotations.*;

import java.util.List;

@Mapper
public interface AdminConnectionMapper {

    @Select("""
        SELECT 
            u.id AS user_id,
            u.username,
            u.level,
            r.last_report_time,
            CASE
                WHEN r.last_report_time IS NOT NULL AND r.event != 'STOPPED'
                     AND r.last_report_time > NOW() - INTERVAL 30 MINUTE THEN true
                ELSE false
            END AS online
        FROM users u
        LEFT JOIN (
            SELECT user_id, MAX(created_at) AS last_report_time, 
                   SUBSTRING_INDEX(GROUP_CONCAT(event ORDER BY created_at DESC), ',', 1) AS event
            FROM tracker_reports
            GROUP BY user_id
        ) r ON u.id = r.user_id
        ORDER BY r.last_report_time DESC
        LIMIT #{limit} OFFSET #{offset}
    """)
    List<UserConnectionStatusDTO> getAllUserConnectionStatus(@Param("offset") int offset,
                                                             @Param("limit") int limit);

    @Select("SELECT COUNT(*) FROM users")
    int countAllUsers();
}

